package net.sunxiaolong.tool.captureinsureknowledge.controller;

import net.sunxiaolong.tool.captureinsureknowledge.entity.PingAnKnowledge;
import net.sunxiaolong.tool.captureinsureknowledge.repository.PingAnKnowledgeRepository;
import net.sunxiaolong.tool.captureinsureknowledge.tool.NetworkTool;
import net.sunxiaolong.tool.captureinsureknowledge.tool.SnowFlakeIdGenerator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 晓龙
 * @create 2018-08-16 下午1:42
 * @desc
 **/
@RestController
@RequestMapping(value = "pingan", method = RequestMethod.POST)
public class PinganCaptureController {

    @Autowired
    private PingAnKnowledgeRepository pingAnKnowledgeRepository;

    @RequestMapping(value = "tieshiCapture")
    public String pingAnTieShiCapture() throws XPatherException {
        String baseUrl = "https://e.pingan.com/pa18shoplife/skills/";
        String listUrl = baseUrl + "bxtslist.shtml";
        HtmlCleaner hc = new HtmlCleaner();
        String listPageContent = NetworkTool.getStringFromUrl(listUrl, null);
        TagNode listPathTn = hc.clean(listPageContent);
        String aPathStr = "//ul[@id='itemContainer']/li/a";
        Object[] aObjArray = listPathTn.evaluateXPath(aPathStr);
        List<PingAnKnowledge> pingAnKnowledgeList = new ArrayList<>();
        for (Object aObj : aObjArray) {
            TagNode aTn = (TagNode) aObj;
            String articleHref = aTn.getAttributeByName("href");
            String absoluteArticleHref = baseUrl + articleHref;
            TagNode emTn = aTn.getChildTags()[0];
            String title = emTn.getText().toString();

            String articlePageContent = NetworkTool.getStringFromUrl(absoluteArticleHref, null);
            TagNode articlePageTn = hc.clean(articlePageContent);
            String contentDivPathStr = "//div[@class='case']";
            TagNode contentDivTn = (TagNode) articlePageTn.evaluateXPath(contentDivPathStr)[0];
            TagNode[] contentDivInnerTnArray = contentDivTn.getChildTags();
            contentDivTn.removeChild(contentDivInnerTnArray[contentDivInnerTnArray.length - 1]);
            String content = contentDivTn.getText().toString().replaceAll("&nbsp;", " ").trim();
            PingAnKnowledge pak = new PingAnKnowledge(SnowFlakeIdGenerator.nextId(), title, content, absoluteArticleHref);
            pingAnKnowledgeList.add(pak);
        }
        pingAnKnowledgeRepository.saveAll(pingAnKnowledgeList);
        return "OK";
    }

    @RequestMapping(value = "bxzszqCapture")
    public String baoXianZhiShiZhuanQuCapture() throws XPatherException {
        String listPageUrl = "https://e.pingan.com/pa18shoplife/skills/bxzslist.shtml";
        String listPageContent = NetworkTool.getStringFromUrl(listPageUrl, null);
        HtmlCleaner hc = new HtmlCleaner();
        TagNode listPageTn = hc.clean(listPageContent);
        String classDivPathStr = "//div[@class='j_cjwt_item']";
        Object[] classDivObjArray = listPageTn.evaluateXPath(classDivPathStr);
        List<PingAnKnowledge> pingAnKnowledgeList = new ArrayList<>();
        for (Object classDivObj : classDivObjArray) {
            TagNode classDivTn = (TagNode) classDivObj;
            TagNode[] classDivInnerTnArray = classDivTn.getChildTags();
            String title = classDivInnerTnArray[0].getText().toString();
            TagNode contentTn = classDivInnerTnArray[1];
            List contentChildrenList = contentTn.getAllChildren();

            StringBuffer thisQuestion = new StringBuffer();
            StringBuffer thisAnswer = new StringBuffer();
            for (int i = 0; i < contentChildrenList.size(); i++) {
                if (contentChildrenList.get(i) instanceof TagNode) {
                    TagNode thisNode = (TagNode) contentChildrenList.get(i);
                    if (thisNode.getName().equalsIgnoreCase("span")) {
                        if (thisQuestion.length() == 0) {
                            thisQuestion.append(title + ":" + thisNode.getText());
                        } else {
                            PingAnKnowledge pak = new PingAnKnowledge(SnowFlakeIdGenerator.nextId(), thisQuestion.toString(), thisAnswer.toString(), listPageUrl);
                            pingAnKnowledgeList.add(pak);
                            thisQuestion = new StringBuffer(title + ":" + thisNode.getText());
                            thisAnswer = new StringBuffer("");
                        }
                    } else {
                        thisAnswer.append(thisNode.getText());
                    }

                } else if (contentChildrenList.get(i) instanceof ContentNode) {
                    ContentNode thisNode = (ContentNode) contentChildrenList.get(i);
                    thisAnswer.append(thisNode.getContent().replaceAll("&nbsp;", "").trim());
                }
            }
            PingAnKnowledge pak = new PingAnKnowledge(SnowFlakeIdGenerator.nextId(), thisQuestion.toString(), thisAnswer.toString(), listPageUrl);
            pingAnKnowledgeList.add(pak);
        }
        pingAnKnowledgeRepository.saveAll(pingAnKnowledgeList);
        return "OK";
    }

    @RequestMapping(value = "changJianWenTiCapture")
    public String changJianWenTiCapture() throws XPatherException {
        String listPageUrlStr = "https://e.pingan.com/pa18shoplife/help/index.jsp";
        HtmlCleaner hc = new HtmlCleaner();
        TagNode listPageTn = hc.clean(NetworkTool.getStringFromUrl(listPageUrlStr, null));
        String divPathStr = "//div[@class='j_cjwt_item']";
        Object[] divObjArray = listPageTn.evaluateXPath(divPathStr);
        List<PingAnKnowledge> pingAnKnowledgeList = new ArrayList<>();
        for (Object divObj : divObjArray) {
            TagNode divTn = (TagNode) divObj;
            TagNode[] divInnerTnArray = divTn.getChildTags();
            String question = divInnerTnArray[0].getText().toString().trim().replaceAll("&nbsp;", " ");
            String answer = divInnerTnArray[1].getText().toString().trim().replaceAll("&nbsp;", " ");
            PingAnKnowledge pak = new PingAnKnowledge(SnowFlakeIdGenerator.nextId(), question, answer, listPageUrlStr);
            pingAnKnowledgeList.add(pak);
        }
        pingAnKnowledgeRepository.saveAll(pingAnKnowledgeList);
        return "OK";
    }


    @RequestMapping(value = "export")
    public String export() throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("平安知识库");
        int rowIndex = 0;
        int cellIndex = 0;
        Row headRow = sheet.createRow(rowIndex++);
        headRow.createCell(cellIndex++).setCellValue("DBID");
        headRow.createCell(cellIndex++).setCellValue("标题");
        headRow.createCell(cellIndex++).setCellValue("内容");
        headRow.createCell(cellIndex++).setCellValue("链接");
        List<PingAnKnowledge> piccKnowledgeList = pingAnKnowledgeRepository.getAllData();
        for (PingAnKnowledge pk : piccKnowledgeList) {
            cellIndex = 0;
            Row thisRow = sheet.createRow(rowIndex++);
            thisRow.createCell(cellIndex++).setCellValue(pk.getId());
            thisRow.createCell(cellIndex++).setCellValue(pk.getTitle());
            thisRow.createCell(cellIndex++).setCellValue(pk.getContent());
            thisRow.createCell(cellIndex++).setCellValue(pk.getHref());
        }
        OutputStream os = new FileOutputStream("/tmp/平安知识库" + System.currentTimeMillis() + ".xlsx");
        workbook.write(os);
        os.close();
        workbook.close();
        return "OK";
    }
}

